package hh.util;

import hh.util.time.TimeUtil;
import hh.util.time.Tunit;
import lombok.Data;

import java.util.Collections;
import java.util.List;

@Data
public class Retry {

    public static void main(String[] args) {
        Retry retry = new Retry("1 min,10min,30min,1h,3h,5h");
        System.out.println(retry.getExpUnits());

        for (int i = 0; i < 20; i++) {
            long nextExecuteTime = retry.getNextExecuteTime();
            System.out.println(nextExecuteTime + " " + TimeUtil.toCn(nextExecuteTime));
        }
    }

    final private List<Tunit> expUnits;
    final String retryExp;//= "1min,10min,30min,1h,3h,5h";
    int retries;

    public Retry(String retryExp) {
        this.retryExp = retryExp;
        this.expUnits = Collections.unmodifiableList(TimeUtil.parseTimeUnits(retryExp));
    }

    public long getNextExecuteTime() {
        long executeTime = getExecuteTime();
        retries++;
        return executeTime;
    }

    public long getExecuteTime() {
        if (retries >= expUnits.size()) {
            return expUnits.get(expUnits.size() - 1).getMillis();
        }
        return expUnits.get(retries).getMillis();
    }

    public long getExecuteTime(int retries) {
        if(retries>=expUnits.size()) retries = expUnits.size() - 1;
        return expUnits.get(retries).getMillis();
    }
}
